package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/emps")
public class EmpController {
    @Autowired
    private EmpService empService;

    @Autowired
    private EmpExprService empExprService;

    @Autowired
    private DeptService deptService;

    @GetMapping
    public Result page(EmpQueryParam param) {
        log.info("员工列表查询条件：{}", param);

        Page<Emp> page = new Page<>(param.getPage(), param.getPageSize());
         page.addOrder(OrderItem.desc("update_time"));
          LambdaQueryWrapper<Emp> lw = new LambdaQueryWrapper<>();
          lw.like(param.getName()!=null && param.getName().length()>0,Emp::getName,param.getName())
                  .eq(param.getGender()!=null,Emp::getGender,param.getGender())
                  .between(param.getBegin()!=null && param.getEnd() != null,Emp::getEntryDate,param.getBegin(),param.getEnd());
        Page<Emp> p = empService.page(page,lw);
        List<Emp> emps = page.getRecords();
        Set<Integer> idSet = emps.stream().map(Emp::getDeptId).filter(Objects::nonNull).collect(Collectors.toSet());
        if ( idSet!=null && idSet.size() > 0){
            List<Dept> depts = deptService.listByIds(idSet);

            Map<Integer, String> collect = depts.stream().filter(Objects::nonNull).collect(Collectors.toMap(Dept::getId, Dept::getName));
            for (Emp emp : emps) {
                emp.setDeptName(collect.get(emp.getDeptId()));
            }
        }
        PageResult<Emp> pageResult = new PageResult<>(p.getTotal(), p.getRecords());

        // 返回结果
        return Result.success(pageResult);
    }
//    public Result page1(EmpQueryParam param){
//        log.info("员工列表查询条件：{}", param);
//        //实现分页
//        Page<Emp> page =new Page<>(param.getPage(),param.getPageSize());
//        //创建lambdaQueryWrapper实现条件查询
//        LambdaQueryWrapper<Emp> lw= new LambdaQueryWrapper<>();
//        lw.like(param.getName()!=null && param.getName().length()>0 ,Emp::getName,param.getName())
//                .eq(param.getGender()!=null ,Emp::getGender,param.getGender())
//                .between(param.getBegin()!=null && param.getEnd()!=null,Emp::getEntryDate,param.getBegin(),param.getEnd());
//        Page<Emp> p = empService.page(page, lw);
//        //得到员工的所有数据
//        List<Emp> emps = page.getRecords();
//        //通过stream流获取员工的deptId
//        Set<Integer> deptId = emps.stream().map(emp -> emp.getDeptId()).filter(emp -> emp != null).collect(Collectors.toSet());
//        //调用deptService实现通过多个id查询部门
//        List<Dept> depts = deptService.listByIds(deptId);
//        //通过stream流将部门id和名字放在map集合中
//        Map<Integer, String> collect = depts.stream().filter(dept -> dept != null).collect(Collectors.toMap(dept -> dept.getId(), dept -> dept.getName()));
//
//        //判断员工不为null
//        if (deptId!=null && deptId.size()>0){
//            //遍历员工拿到员工对应的部门id设置对应的部门名称
//            for (Emp emp : emps) {
//                emp.setDeptName(collect.get(emp.getDeptId()));
//            }
//        }
//        PageResult<Emp> pageResult =new PageResult<>(p.getTotal(),p.getRecords());
//        return Result.success(pageResult);
//    }
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public Result save(@RequestBody Emp emp) {
        log.info("新增员工，员工信息：{}", emp);

        // 调用service层方法保存员工信息和员工的工作经历信息
        // 1. 保存员工基本信息
        // 补全基础属性
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        empService.saveEmp(emp);



        return Result.success();
    }

    @DeleteMapping
    @Transactional(rollbackFor = Exception.class)
    public Result delete(@RequestParam List<Integer> ids) {
        log.info("批量删除学生，{}", ids);

        // 调用service层方法批量删除员工信息
        empService.deleteByEmpIds(ids);



        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据ID查询员工信息，id：{}", id);

        // 调用Service层方法查询员工基本信息
        Emp emp = empService.getByEmpId(id);


        return Result.success(emp);
    }

    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public Result update(@RequestBody Emp emp) {
        log.info("修改员工信息，员工信息：{}", emp);
        // 1.保存员工的基本信息
        empService.updateEmpById(emp);



        // 调用service层方法修改员工信息
        return Result.success();
    }

    @GetMapping("/list")
    public Result list() {
        log.info("查询员工列表");
        List<Emp> list = empService.list();
        // 调用service层方法查询员工列表
        return Result.success(list);
    }
}
